package admin

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/hibiken/asynq"
	"zhuandan/models"
)

const (
	TypeTuiSong = "tui:song"
	redisAddr   = "127.0.0.1:6379"
)

var client *asynq.Client

func init() {
	client = asynq.NewClient(asynq.RedisClientOpt{Addr: redisAddr})

	srv := asynq.NewServer(
		asynq.RedisClientOpt{Addr: redisAddr},
		asynq.Config{
			Concurrency: 10,
			Queues: map[string]int{
				"critical": 6,
				"default":  3,
				"low":      1,
			},
		},
	)

	mux := asynq.NewServeMux()
	mux.HandleFunc(TypeTuiSong, HandleTuiSongTask)

	if err := srv.Start(mux); err != nil {
		fmt.Printf("could not run server: %v \n", err)
	}
}

type TuiSongTaskPayload struct {
	User    models.User    `json:"user"`
	Procure models.Procure `json:"procure"`
}

func NewTuiSongTask(user models.User, procure models.Procure) (*asynq.Task, error) {
	payload, err := json.Marshal(TuiSongTaskPayload{
		User:    user,
		Procure: procure,
	})
	if err != nil {
		return nil, err
	}
	return asynq.NewTask(TypeTuiSong, payload, asynq.MaxRetry(5)), nil
}

func HandleTuiSongTask(ctx context.Context, t *asynq.Task) error {
	var p TuiSongTaskPayload
	if err := json.Unmarshal(t.Payload(), &p); err != nil {
		return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry)
	}
	ConsumeTuisongywd(p.User, p.Procure)
	return nil
}
